<template>
  <div
    v-loading="loading"
    element-loading-text="加载中..."
    style="position: relative; display: flex; flex-direction: column; height: 100%"
  >
    <div class="top">
      <div class="nav">
        <el-tabs v-model="activeName" class="demo-tabs" @tab-change="tabClick">
          <!--全部结算单-->
          <el-tab-pane :name="0">
            <template #label>
              <span>全部结算单（{{ OrderStatusQtyData?.total || 0 }}）</span>
            </template>
          </el-tab-pane>

          <!--待结算-->
          <el-tab-pane :name="1">
            <template #label>
              <span class="custom-tabs-label">
                <span>待结算（{{ OrderStatusQtyData?.waitOrderSettlementQty || 0 }}）</span>
              </span>
            </template>
          </el-tab-pane>

          <!--已结算-->
          <el-tab-pane :name="2">
            <template #label>
              <span class="custom-tabs-label">
                <span>已结算（{{ OrderStatusQtyData?.orderSettlementQty || 0 }}）</span>
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
    <div class="app-container" style="display: flex; flex-direction: column; height: 100%">
      <div class="app-container-inner" style="display: flex; flex-direction: column">
        <div class="search">
          <!--日期类型-->
          <el-select
            v-model="dateType"
            class="date-type"
            placeholder="日期类型"
            clearable
            @change="
              () => {
                radio1 = 4
                getOrderListData()
              }
            "
            @clear="getOrderListData"
          >
            <el-option
              v-for="item in dateTypeSele"
              :key="item.val"
              :value="item.val"
              :label="item.name"
            />
          </el-select>

          <!--选择时间-->
          <el-select
            v-if="dateType"
            v-model="radio1"
            class="select-date"
            placeholder="选择时间"
            clearable
            @change="radio1 == 1 ? '' : getOrderListData()"
          >
            <el-option
              v-for="item in timeOptions"
              :key="item.value"
              :value="item.value"
              :label="item.title"
            />
          </el-select>

          <!--日期范围-->
          <div v-if="radio1 == 1" class="date-range">
            <DateRange ref="dateRangeRef" @change="handleDateChange" />
          </div>

          <!--下拉选择-->
          <!-- <div class="btn_dropdown">
            <div class="btn_dropdown_type">
              <el-dropdown @command="handleCommand1" trigger="click">
                <span style="font-size: 12px">
                  {{ orderByTypeList[orderByType - 1].name }}
                  <el-icon>
                    <ArrowDown />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="i in orderByTypeList"
                      :key="i.value"
                      :command="i.value"
                    >
                      {{ i.name }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="btn_dropdown_sort">
              <el-dropdown @command="handleCommand2" trigger="click">
                <span style="margin-left: 5px; font-size: 12px">
                  {{ orderBySortList[orderBySort - 1].name }}
                  <el-icon>
                    <ArrowDown />
                  </el-icon>
                </span>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      v-for="i in orderBySortList"
                      :key="i.value"
                      :command="i.value"
                    >
                      {{ i.name }}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div> -->

          <!--工单单号-->
          <el-input
            v-model.trim="input1"
            clearable
            placeholder="工单单号"
            class="order-no"
            @keyup.enter="getOrderListData"
            @clear="getOrderListData"
          />

          <!--设备拍拍/名称/型号-->
          <el-input
            v-model.trim="goodsKeyword"
            clearable
            placeholder="设备品牌/名称/型号"
            class="search-good"
            @keyup.enter="getOrderListData"
            @clear="getOrderListData"
          />

          <!--客户名称/手机号/地址-->
          <el-input
            v-model.trim="input4"
            clearable
            placeholder="客户名称/手机号/地址"
            class="search-user"
            @keyup.enter="getOrderListData"
            @clear="getOrderListData"
          />

          <!--按钮组-->
          <div class="btn-group">
            <HButton type="primary" @click="getOrderListData">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </HButton>
            <HButton @click="clearValue">
              <el-icon>
                <RefreshRight />
              </el-icon>
              重置
            </HButton>
          </div>
        </div>
        <div class="table-list" style="flex: 1; position: relative">
          <el-table
            ref="tableList"
            height="100%"
            style="position: absolute"
            :border="true"
            stripe
            resizable
            :data="tableDataList"
            @row-dblclick="goDetail"
          >
            <template #empty>
              <el-empty description="暂无数据" />
            </template>
            <!--序号-->
            <el-table-column
              type="index"
              label="序号"
              fixed="left"
              min-width="50"
              :align="'center'"
            />
            <template v-for="(item, index) in OrderListTable" :key="index">
              <el-table-column
                v-if="item.showColumn"
                show-overflow-tooltip
                :fixed="item.freezeColumn"
                :align="item.code == 'totalPrice' ? 'right' : 'left'"
                :prop="item.code"
                :label="item.name"
                :width="tableColumnWidth[item.code] ? tableColumnWidth[item.code] : 140"
              >
                <!--  -->
                <template v-if="item.code == 'code'" #default="scope">
                  <span v-if="scope.row.isRepeatOrder" class="repeat">重</span>
                  <span v-if="scope.row.remindersStatus" class="reminder">催</span>
                  <span class="number" @click="goDetail(scope.row)">{{ scope.row.code }}</span>
                </template>

                <!-- 工单类型 -->
                <template v-if="item.code == 'module'" #default="scope">
                  <span>{{ scope.row.module }}</span>
                </template>

                <!--状态 -->
                <template v-if="item.code == 'status'" #default="scope">
                  <HStatus v-if="scope.row.status === 1" type="warning">待派单</HStatus>
                  <HStatus v-if="scope.row.status === 2" type="warning">待部门确认</HStatus>
                  <HStatus v-if="scope.row.status === 3" type="warning">处理中</HStatus>
                  <HStatus v-if="scope.row.status === 4" type="success">已完成</HStatus>
                  <HStatus v-if="scope.row.status === 5" type="info">已取消</HStatus>
                </template>

                <!--  等级 -->
                <template v-if="item.code == 'level'" #default="scope">
                  <span :style="{ color: scope.row.workLevelColor }">{{
                    scope.row.workLevel
                  }}</span>
                </template>

                <!-- 公司地址 -->
                <template v-if="item.code == 'userAddress'" #default="i">
                  <span>{{
                    i.row.province + i.row.city + i.row.area + i.row.town + i.row.address
                  }}</span>
                </template>

                <template v-if="item.code == 'totalPrice'" #default="i">
                  <span>￥{{ i.row.totalPrice.toFixed(2) }}</span>
                </template>
                <!--  服务时长 -->
                <template v-if="item.code == 'totalServiceTime'" #default="scope">
                  <span :style="{ color: scope.row.serviceTimeColor }">{{
                    scope.row.serviceTime
                  }}</span>
                </template>
                <!--工单来源  -->
                <template v-if="item.code == 'source'" #default="i">
                  <span v-for="item in sources" :key="item.value">
                    <span v-if="i.row.source == item.value">{{ item.title }}</span>
                  </span>
                </template>
              </el-table-column>
            </template>
            <!-- 自定义字段 -->
            <el-table-column
              v-for="(key, index) in arrList"
              :key="index"
              show-overflow-tooltip
              min-width="160"
              :label="key.name"
            >
              <template #default="i">
                <template v-for="item in i.row.fieldVals">
                  {{ item.id == key.id ? item.val : '' }}
                </template>
              </template>
            </el-table-column>
            <!-- 表单设置 -->
            <el-table-column
              :align="'center'"
              fixed="right"
              width="50"
              label-class-name="table_setting"
            >
              <template #header>
                <el-tooltip effect="dark" content="列表设置" placement="top-start">
                  <i class="iconfont icon-liebiaoshezhi-list-setting" @click="tableShowSet"></i>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="pagination">
          <Pagination
            ref="pagination"
            :list_total="totalList"
            @size-change="getOrderListData"
            @current-change="getOrderListData(false)"
          />
        </div>
        <!-- <AssignDialog :assignAny="assignAny" :assignDialog="assignDialog" :selecttion="selecttion"
            @assign-dialog="assignDialog = false, isbatch = true" :isbatch="isbatch"
            @update-list="getOrderListData(), selecttion = [], arr = []">
          </AssignDialog> -->
        <!-- 工单导出弹窗 -->
        <!-- 列表设置 -->
        <table-column-set
          v-model="dialogTableVisible"
          :type="3"
          @update-list="getOrderListData(), getOrderListTableFieldList()"
          @set-table-dialog="dialogTableVisible = $event"
        />
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, onMounted } from 'vue'
  import { useRouter } from 'vue-router'
  import type { TabsPaneContext } from 'element-plus'
  import { Search, RefreshRight, ArrowDown } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import Pagination from '../../../components/Pagination/index.vue'
  import { getOrderListTableTitleField, getOrderListTableField } from '../../../api/order'
  import { getOrderSettlementList, getOrderSettlementStatusQty } from '../../../api/settlement'
  import TableColumnSet from '@/components/pages/order/common/table-column-set/TableColumnSet.vue'
  import * as _ from 'lodash'
  import setSvg from '@/assets/order/set.svg'
  import DateRange from '@/components/DateRange.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HStatus from '@/components/common/status/HStatus.vue'

  const tableDataList: any = ref(null) //工单列表数据
  const OrderStatusQtyData: any = ref(null) //工单状态数量数据

  const activeName = ref(0)
  const router = useRouter()
  const loading = ref(false)

  const pagination = ref()
  const totalList = ref(0) //列表总数量
  const dateType = ref<'' | 1 | 2 | 3>(3)
  const dateTypeSele = ref([
    { name: '报单日期', val: 1 },
    { name: '结算日期', val: 2 },
    { name: '完工日期', val: 3 },
  ])
  let arrList = ref([]) //自定义字段
  const orderByTypeList = ref([
    { name: '完工时间', value: 1 },
    { name: '结算时间', value: 2 },
    { name: '取消时间', value: 3 },
  ])
  const orderBySortList = ref([
    { name: '升序', value: 1 },
    { name: '降序', value: 2 },
  ])
  // 搜索栏
  const input1 = ref('') // 工单编号
  const input4 = ref('') //搜索客户名称/手机号/地址
  const tableList = ref() // 表格Dom

  // 表格列宽
  const tableColumnWidth = {
    status: '118',
    userPhone: '104',
    createTime: '128',
  }

  // 表头搜索
  const value2 = ref('') // 申请时间
  const startTime: any = ref(null) // 开始日期
  const endTime: any = ref(null) // 结束日期
  // 筛选 1-报单时间 3-部门 4-服务时长
  const radio1 = ref(null)
  const radio4 = ref(null)

  // 报单时间
  const timeOptions = ref([
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '自定义时间', value: 1 },
  ])

  // 工单来源
  const sources = ref([
    // { title: '系统报单', value: 1 },
    { title: '线下工单', value: 1 },
    { title: '公司小程序报单', value: 2 },
    { title: '工程师小程序报单', value: 3 },
    // { title: '公司APP报单', value: 4 },
    // { title: 'Excel导入工单', value: 5 },
    // { title: '400工单', value: 6 },
    // { title: '公众号报单', value: 7 },
    // { title: '神州联保第三方报单', value: 8 },
    // { title: '万师傅第三方报单', value: 9 },
    // { title: '公司H5端报单', value: 10 },
    // { title: '快可立第三方', value: 11 },
    // { title: '工程师H5端报单', value: 12 },
  ])

  // 导航切换
  const tabClick = (tab: TabsPaneContext) => {
    activeName.value = Number(tab)
    getOrderListData()
  }
  // 排序字段类型
  const handleCommand1 = (val) => {
    if (orderByType.value != val) {
      orderByType.value = val
      getOrderListData()
    }
  }
  // 排序类型
  const handleCommand2 = (val) => {
    if (orderBySort.value != val) {
      orderBySort.value = val
      getOrderListData()
    }
  }
  // 重置
  const clearValue = () => {
    if (dateRangeRef.value) {
      dateRangeRef.value.resetDateRange()
    }
    isStartDateGreaterThanEndDate.value = false
    dateType.value = 3
    radio1.value = null
    input1.value = ''
    goodsKeyword.value = ''
    input4.value = ''
    value2.value = ''
    startTime.value = null
    endTime.value = null
    radio4.value = null
    getOrderListData()
  }
  // 查看工单详细
  const goDetail = (val: any) => {
    router.push('/order/odetail/' + val.id + '?isArchive=true')
  }

  // 日期范围组件实例
  const dateRangeRef = ref<InstanceType<typeof DateRange> | null>(null)

  // 开始日期是否大于结束日期
  const isStartDateGreaterThanEndDate = ref(false)

  // 日期更新事件
  const handleDateChange = (param: {
    startDate: string
    endDate: string
    isStartDateGreaterThanEndDate: boolean
  }) => {
    if (param.isStartDateGreaterThanEndDate) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
        plain: true,
      })
      return false
    }
    startTime.value = param.startDate
    endTime.value = param.endDate
    isStartDateGreaterThanEndDate.value = param.isStartDateGreaterThanEndDate
    getOrderListData()
  }
  const orderBySort = ref(2) // 排序类型：1-升序，2-降序,示例值(2)
  const orderByType = ref(2) // 排序字段类型：1-完工时间，2-结算时间，3-取消时间,示例值(2)
  const goodsKeyword = ref('') // 工单设备关键词搜索：设备品牌/名称/型号

  // 获取工单给算列表
  const getOrderListData = _.debounce(async (val = true) => {
    if (isStartDateGreaterThanEndDate.value) {
      ElMessage({
        type: 'error',
        message: '开始日期不能大于结束日期',
      })
      return
    }

    let itmeType: any = null
    if (radio1.value) {
      // 筛选条件 时间类型
      itmeType = radio1.value
    }
    let tab: any = null
    if (activeName.value === 0) {
      //判断是切换为全部工单
      tab = null
    } else {
      tab = activeName.value - 1
    }
    if (val) {
      pagination.value.setPage()
    }
    let data: any = {
      dateType: dateType.value, // 报单时间类型
      dateValType: itmeType, // 日期参数类型：1-时间区间，2-今天，3-本周，4-本月，5-过去三个月
      goodsKeyword: goodsKeyword.value, // 工单设备关键词搜索：设备品牌/名称/型号
      limit: pagination.value.size, // 每页显示数量
      orderBySort: orderBySort.value, //
      orderByType: orderByType.value, //
      orderEndTime: endTime.value, // 报单/结算/完工结束日期
      orderStartTime: startTime.value, // 报单/结算/完工开始日期
      page: pagination.value.current, // 当面页码
      status: tab, // 结算状态：0-待结算，1-已结算
      userKeyword: input4.value.trim(), // 公司关键词：客户名称/手机号/地址
      workNo: input1.value.trim(), // 工单单号
    }
    loading.value = true
    const res = await getOrderSettlementList(data)
    if (res.data.success) {
      tableDataList.value = res.data.data.rows
      totalList.value = Number(res.data.data.total)
      getOrderStatusQtyData()
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200,
      })
    }
    loading.value = false
  }, 0)

  // 获取工单归档列表状态数量
  const getOrderStatusQtyData = async () => {
    const res = await getOrderSettlementStatusQty()
    if (res.data.success) {
      OrderStatusQtyData.value = res.data.data.row
    } else {
      ElMessage({
        showClose: true,
        message: res.data.message,
        type: 'error',
        duration: 4000,
        offset: 200,
      })
    }
  }
  const getOrderListTableTitleFieldList = async () => {
    const res = await getOrderListTableTitleField()
    if (res.data.success) {
      arrList.value = res.data.data.rows
    }
  }
  // 获取工单列表表头字段
  const dialogTableVisible = ref(false)
  const OrderListTable: any = ref(null)
  const getOrderListTableFieldList = () => {
    getOrderListTableField(3).then((res) => {
      if (res) {
        OrderListTable.value = res.data.data.rows
      }
    })
  }
  // 点击列表设置
  const tableShowSet = () => {
    dialogTableVisible.value = true
  }

  onMounted(() => {
    new Promise(() => {
      getOrderListData()
      getOrderListTableTitleFieldList()
      getOrderListTableFieldList()
    })
  })
</script>

<style scoped lang="scss">
  :deep(.table_setting) {
    padding: 0 !important;

    .cell {
      height: 100%;
      padding: 0;
      display: flex;
      align-items: center;
      justify-content: center;

      .iconfont {
        font-size: 24px;
        width: 24px;
        height: 20px;
        color: $primaryColor;
        margin: 0;
      }
    }
  }

  .top {
    padding: 12px 12px 0;

    .nav {
      height: 100%;
      width: 100%;
      background: #ffffff;
      padding: 0 12px 12px;
      box-sizing: border-box;

      .demo-tabs {
        :deep(.el-tabs__header) {
          margin: 0;

          .el-tabs__nav-wrap {
            .el-tabs__nav {
              .el-tabs__item {
                padding: 0 10px;

                .icon {
                  font-size: 12px;
                  padding: 0 3px;
                  margin-left: 5px;
                  border-radius: 2px;
                }
              }

              .el-tabs__item.is-top:nth-child(2) {
                padding-left: 0;
              }
            }
          }
        }

        :deep(.el-tabs__nav-wrap::after) {
          height: 1px;
        }
      }
    }
  }

  .search {
    display: flex;
    justify-content: end;
    height: 28px;
    margin-bottom: 11px;
    gap: 5px;

    .date-type {
      width: 100px;
    }

    .select-date {
      width: 100px;
    }

    .order-no {
      width: 120px;
    }

    .search-good {
      width: 140px;
    }

    .search-user {
      width: 160px;
    }

    .btn-group {
      display: flex;
      align-items: center;
      gap: 5px;
      height: 28px;

      .search-btn,
      .reset-btn {
        height: 28px;
        padding: 0 6px;
        display: flex;
        align-items: center;
        border-radius: 2px;
        border-width: 1px;
        border-style: solid;
        cursor: pointer;
      }
    }

    .btn_dropdown {
      box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
      height: 26px;
      border-radius: 2px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      padding: 1px 11px;

      .btn_dropdown_type {
        padding: 1px 11px;
        height: 25px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 12px;
      }

      .btn_dropdown_sort {
        border-left: 1px solid #dcdfe6;
        padding: 1px 11px;
        height: 25px;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-size: 12px;
      }
    }
  }

  .btns {
    margin: 10px 0;

    .btn {
      display: flex;
      align-items: center;

      .iconfont {
        margin-right: 5px;
      }

      .icon-shangjifenpai_line {
        transform: rotateY(180deg);
      }
    }

    .mr5 {
      margin-right: 5px;
    }
  }

  .pagination {
    padding: 12px 0 0;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }

  .select-time {
    margin: 10px 0;

    :deep(.el-date-editor) {
      width: 200px;
      height: 28px;
      margin-bottom: 5px;
    }
  }

  .table-list {
    .iconfont {
      margin-left: auto;
      font-size: 12px;
      cursor: pointer;
    }

    .number {
      color: #007cff;
      cursor: pointer;

      &:hover {
        text-decoration: underline;
      }
    }

    .repeat {
      display: inline-block;
      font-size: 12px;
      line-height: 20px;
      padding: 0 4px;
      margin-right: 8px;
      border-radius: 2px;
      color: #fff;
      background: #f56c6c;
      cursor: pointer;
    }

    .reminder {
      display: inline-block;
      font-size: 12px;
      line-height: 20px;
      padding: 0 4px;
      margin-right: 8px;
      border-radius: 2px;
      color: #fff;
      background: #e69103;
    }

    .module {
      display: inline-block;
      font-size: 12px;
      line-height: 22px;
      padding: 0 6px;
      border-radius: 2px;
      color: #383838;
      background: #e6eaf0;
    }

    .status {
      display: inline-block;
      font-size: 12px;
      line-height: 22px;
      padding: 0 6px;
      border-radius: 2px;
    }

    .bg-status1 {
      color: #00c0c0;
      background: #e1f8f8;
    }

    .bg-status2 {
      color: #e69103;
      background: #fdf4de;
    }

    .bg-status3 {
      color: #007cff;
      background: #e6f1ff;
    }

    .bg-status4 {
      color: #f56c6c;
      background: #f5efef;
    }

    .select-work {
      display: inline-block;
      font-size: 12px;
      padding: 0 4px;
      border-radius: 2px;
      color: #ffffff;
      background-color: #00c0c0;
      cursor: pointer;
    }

    :deep(td.el-table-fixed-column--right) {
      display: none;
    }
  }

  .el-select-dropdown.is-multiple .el-select-dropdown__item.selected::after {
    width: 16px;
    height: 16px;
    background-color: #007cff;
  }

  .btn_save {
    width: 60px;
  }

  .btn_delete {
    width: 60px;
    color: #fff;
  }

  .btn_cancel {
    width: 60px;

    &:hover {
      border: 1px solid #e5e5e5;
      color: #999;
      background-color: #e5e5e5;
    }
  }

  .el-tag.el-tag--success {
    --el-tag-text-color: #00c0c0;
    --el-tag-bg-color: #ebf6f6;
    --el-tag-border-color: #ebf6f6;
    --el-tag-hover-color: #00c0c0;
  }

  .el-tag.el-tag--info {
    --el-tag-border-color: var(--el-color-info-light-9);
  }

  .el-tag {
    --el-tag-border-color: var(--el-color-primary-light-9);
  }

  .el-tag.el-tag--warning {
    --el-tag-border-color: var(--el-color-warning-light-9);
  }
</style>
